package com.deepclassifieds.daas.api.util;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public final class XMLGregorianCalendarHelper {
	
	private XMLGregorianCalendarHelper() {}
	
	public static Date toDate(XMLGregorianCalendar xcal) {
		return xcal != null ? xcal.toGregorianCalendar().getTime() : null;		
	}

    public static XMLGregorianCalendar parse(String lexicalRepresentation) {
        if (lexicalRepresentation == null) return null;
        try {
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalRepresentation);
        } catch (DatatypeConfigurationException ex) {
            throw new RuntimeException(ex);
        }
    }
	
    public static XMLGregorianCalendar toXMLGregorianCalendar(Date date) {
        if (date == null) return null;
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        try {
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        } catch (DatatypeConfigurationException ex) {
            return null;
        }
    }

}
